package com.cqywc.cjadmin.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.cqywc.cjadmin.service.ReturnSerivice;
import com.sun.org.apache.bcel.internal.generic.NEW;

@Controller
@RequestMapping("admin/")
public class AdminIndex {
	@Autowired
	private ReturnSerivice returnSerivice;

	@RequestMapping("index.do")
	public String index() {
		System.out.println(123);
		return "admin/index";
	}

	@RequestMapping("main.do")
	public String main() {
		return "admin/main";
	}
	
	/**
	 * 图片上传
	 * @param avatar
	 * @param request
	 * @return
	 */
	@RequestMapping("uploadImg")
	@ResponseBody
	public ReturnSerivice uploadImg(MultipartFile image,HttpServletRequest request) {
		String myFileName = image.getOriginalFilename();// 文件原名称
		System.out.println(myFileName);
		String fileName= UUID.randomUUID().toString();
		String realPath = ("/upload/images/");
		
		//sdfsd 
		
		Date date=new Date();
		String timePathString=new SimpleDateFormat("yyyyMMdd").format(date);
		File fileDir = new File(realPath + timePathString);
		if (!fileDir.exists()) {
			fileDir.mkdirs();
		}
		
		String locaPath=realPath + timePathString+"/"+fileName+myFileName.substring(myFileName.lastIndexOf("."));
		System.out.println(locaPath);
		File localFile = new File(locaPath); 
		
		try {
			image.transferTo(localFile);
		} catch (IllegalStateException | IOException e) {
			returnSerivice.setCode(100);
			returnSerivice.setMsg("上传失败");
			return returnSerivice;
		}
		returnSerivice.setCode(0);
		Map<String, Object> data=new HashMap<String, Object>();
		data.put("url", "upload/images/"+timePathString+"/"+fileName+myFileName.substring(myFileName.lastIndexOf(".")));
		returnSerivice.setData(data);
		return returnSerivice;
	}

}
